package com.cy.aircompressor.main.home.fragment.v1;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.TimeUtils;
import com.bumptech.glide.Glide;
import com.cy.aircompressor.R;
import com.cy.aircompressor.config.AirConfig;
import com.cy.aircompressor.databinding.FragmentContentMainBinding;
import com.cy.aircompressor.entity.compressor.Compressor;
import com.cy.aircompressor.entity.maintenance.MaintenanceRecord;
import com.cy.aircompressor.entity.sensor.Sensor;
import com.cy.aircompressor.entity.sensor.SensorAgg;
import com.cy.aircompressor.entity.sensor.SensorBgg;
import com.cy.aircompressor.entity.sensor.SensorLineChartData;
import com.cy.aircompressor.entity.sensor.SensorLatestData;
import com.cy.aircompressor.entity.system.SysConfig;
import com.cy.aircompressor.entity.warning.WarningMsg;
import com.cy.aircompressor.main.home.lifecycle.detail.MaintenanceDetailDialog;
import com.cy.aircompressor.main.home.other.WarningDetailFragment;
import com.cy.aircompressor.main.home.fragment.provider.CompressorAdapter;
import com.cy.aircompressor.main.home.fragment.provider.SpeedRmsProvider;
import com.cy.aircompressor.main.home.fragment.provider.TemperaturePressureProvider;
import com.cy.aircompressor.main.home.fragment.provider.MaintenanceRecordProvider;
import com.cy.aircompressor.main.home.fragment.provider.WarningMsgProvider;
import com.cy.aircompressor.main.view.BottomBarTab;
import com.drug.lib.util.DLog;
import com.drug.lib.view.recycptr.DynamicAdpTypePool;
import com.drug.lib.view.recycptr.DynamicRecyclerAdapter;
import com.drug.lib.view.recycptr.OnItemClickListener;
import com.youth.banner.indicator.CircleIndicator;
import com.youth.banner.transformer.AlphaPageTransformer;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import me.yokeyword.fragmentation.SupportFragment;

public class MainContentHelper {
    private FragmentContentMainBinding mBinding;
    private SupportFragment supportFragment;
    private Context mContext;

    public String[] pointCodes = {"temperature", "pressure", "pressure_water,pressure_oil"};
    public String[] pointCodes2 = {"vibration1", "vibration2", "vibration3"};

    public DynamicRecyclerAdapter warningMsgAdapter;
    public DynamicRecyclerAdapter maintenanceRecordAdapter;
    public DynamicRecyclerAdapter temperaturePressureAdapter;
    public DynamicRecyclerAdapter speedRmsAdapter;
    public CompressorAdapter compressorAdapter;
    public RecyclerView.RecycledViewPool mPool;

    public List<Compressor> compressors;
    public List<Sensor> currentSensors;
    public Compressor currentCompressor;

    public int readyNo = 0;
    public String startTime;
    public String endTime;

    private static class SingletonHolder {
        private static final MainContentHelper INSTANCE = new MainContentHelper();
    }

    public static MainContentHelper get() {
        return MainContentHelper.SingletonHolder.INSTANCE;
    }

    public void init(FragmentContentMainBinding mainBinding, SupportFragment supportFragment, Context mContext) {
        this.mBinding = mainBinding;
        this.supportFragment = supportFragment;
        this.mContext = mContext;
        mPool = new RecyclerView.RecycledViewPool();
        mPool.setMaxRecycledViews(0, 10);
        updateTime();
        startTimer();
        initBottomBar();
        initWarningMsgRecycler();
        initMaintenanceRecordRecycler();
        initTemperaturePressureRecycler();
        initSpeedRmsRecycler();
        initBanner();
    }

    private void initWarningMsgRecycler() {
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(mContext);
        mBinding.warningRecyc.setLayoutManager(mLayoutManager);
        warningMsgAdapter = new DynamicRecyclerAdapter();
        DynamicAdpTypePool pool = new DynamicAdpTypePool();
        WarningMsgProvider warningMsgProvider = new WarningMsgProvider();
        pool.register(WarningMsg.class, warningMsgProvider);
        warningMsgAdapter.registerAll(pool);
        mBinding.warningRecyc.setAdapter(warningMsgAdapter);

        warningMsgAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull DynamicRecyclerAdapter adapter, @NonNull View view, int position) {
                List<WarningMsg> warningMsgs = warningMsgAdapter.getItems();
                warningMsgs.forEach(new Consumer<WarningMsg>() {
                    @Override
                    public void accept(WarningMsg warningMsg) {
                        warningMsg.setSelect(false);
                    }
                });
                warningMsgs.get(position).setSelect(true);
                warningMsgAdapter.notifyDataSetChanged();
                WarningDetailFragment warningDetailFragment = WarningDetailFragment.showDialogFragment(supportFragment.getChildFragmentManager(), "detail", warningMsgs.get(position));
                warningDetailFragment.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        warningMsgs.get(position).setSelect(false);
                        warningMsgAdapter.notifyItemChanged(position);
                    }
                });
            }
        });
    }

    private void initMaintenanceRecordRecycler() {
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(mContext);
        mBinding.maintenanceRecordRecyc.setLayoutManager(mLayoutManager);
        maintenanceRecordAdapter = new DynamicRecyclerAdapter();
        DynamicAdpTypePool pool = new DynamicAdpTypePool();
        MaintenanceRecordProvider maintenanceRecordProvider = new MaintenanceRecordProvider();
        pool.register(MaintenanceRecord.class, maintenanceRecordProvider);
        maintenanceRecordAdapter.registerAll(pool);
        mBinding.maintenanceRecordRecyc.setAdapter(maintenanceRecordAdapter);

        maintenanceRecordAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull DynamicRecyclerAdapter adapter, @NonNull View view, int position) {
                List<MaintenanceRecord> maintenanceRecords = maintenanceRecordAdapter.getItems();
                maintenanceRecords.forEach(new Consumer<MaintenanceRecord>() {
                    @Override
                    public void accept(MaintenanceRecord maintenanceRecord) {
                        maintenanceRecord.setSelect(false);
                    }
                });
                maintenanceRecords.get(position).setSelect(true);
                maintenanceRecordAdapter.notifyDataSetChanged();
                MaintenanceDetailDialog maintenanceDetailDialog = MaintenanceDetailDialog.showDialogFragment(supportFragment.getChildFragmentManager(), "detail", maintenanceRecords.get(position).getId());
                maintenanceDetailDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        maintenanceRecords.get(position).setSelect(false);
                        maintenanceRecordAdapter.notifyItemChanged(position);
                    }
                });
            }
        });
    }

    private void initTemperaturePressureRecycler() {
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(mContext);
        mBinding.temperaturePressureRealData.setLayoutManager(mLayoutManager);
        setRecyclerView(mBinding.temperaturePressureRealData);

        temperaturePressureAdapter = new DynamicRecyclerAdapter();
        DynamicAdpTypePool pool = new DynamicAdpTypePool();
        TemperaturePressureProvider provider = new TemperaturePressureProvider(supportFragment.getChildFragmentManager(), mContext);
        pool.register(SensorLineChartData.class, provider);
        temperaturePressureAdapter.registerAll(pool);
        mBinding.temperaturePressureRealData.setAdapter(temperaturePressureAdapter);
    }

    private void initSpeedRmsRecycler() {
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(mContext);
        mBinding.vibrationRealData.setLayoutManager(mLayoutManager);
        setRecyclerView(mBinding.vibrationRealData);
        speedRmsAdapter = new DynamicRecyclerAdapter();
        DynamicAdpTypePool pool = new DynamicAdpTypePool();
        SpeedRmsProvider provider = new SpeedRmsProvider(supportFragment.getChildFragmentManager(), mContext);
        pool.register(SensorLineChartData.class, provider);
        speedRmsAdapter.registerAll(pool);
        mBinding.vibrationRealData.setAdapter(speedRmsAdapter);
    }

    private void setRecyclerView(RecyclerView recyclerView) {
        recyclerView.setItemAnimator(null);
        recyclerView.setItemViewCacheSize(5);
        recyclerView.setDrawingCacheEnabled(true);
        recyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
        recyclerView.setRecycledViewPool(mPool);

    }

    private void initBottomBar() {

        SysConfig sysConfig = AirConfig.get().sysConfig;
        Glide.with(mContext)
                .load(sysConfig.getSysLogo())
                .into(mBinding.systemLogo);
        mBinding.systemName.setText(sysConfig.getSysName());
        mBinding.etUsername.setText(AirConfig.get().userInfo.getName());
        mBinding.bottomBar
                .addItem(new BottomBarTab(mContext, 0, mContext.getString(R.string.nav_zxjc)))
                .addItem(new BottomBarTab(mContext, 0, mContext.getString(R.string.nav_sjfx)))
                .addItem(new BottomBarTab(mContext, 0, mContext.getString(R.string.nav_smzqgl)))
                .addItem(new BottomBarTab(mContext, 0, mContext.getString(R.string.nav_xtsz)));

    }

    public void initBanner() {
        compressorAdapter = new CompressorAdapter(mContext, new ArrayList<>());
        mBinding.banner.addBannerLifecycleObserver(supportFragment)//添加生命周期观察者
                .setAdapter(compressorAdapter)
                .setIndicator(new CircleIndicator(mContext))
                .setBannerGalleryEffect(10, 5) //添加画廊效果
                .setIndicatorNormalWidth(0)
                .setIndicatorSelectedWidth(0)
                .addPageTransformer(new AlphaPageTransformer(0.3f));

    }

    /**
     * 展示所有空压机运行状态
     *
     * @param total
     */
    public void setCompressorToUi(int total) {
        List<Compressor> runningCompressor = compressors.stream()
                .filter(new Predicate<Compressor>() {
                    @Override
                    public boolean test(Compressor compressor) {
                        return compressor.getRunningState() == 1;
                    }
                }).collect(Collectors.toList());
        mBinding.airNum.setText(String.valueOf(total));
        mBinding.airRunning.setText(String.valueOf(runningCompressor.size()));
        mBinding.airStoping.setText(String.valueOf(compressors.size() - runningCompressor.size()));
    }

    private void updateTime() {
        Calendar calendar = Calendar.getInstance();
        mBinding.timeText.setText(TimeUtils.date2String(calendar.getTime(), "HH:mm:ss"));
        mBinding.dateText.setText(TimeUtils.date2String(calendar.getTime(), "yyyy-MM-dd"));
        mBinding.weekText.setText(TimeUtils.getChineseWeek(calendar.getTime()));
    }

    private void startTimer() {
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        updateTime();
                    }
                });
            }
        }, 0, 1000);
    }

    //切换空压机时 先清空原有数据
    public void resetAllAdapter() {
        List<SensorLineChartData> sensorLineChartDatas = initTemperaturePressureDatas();
        temperaturePressureAdapter.setItems(sensorLineChartDatas);
        temperaturePressureAdapter.notifyDataSetChanged();

        List<SensorLineChartData> speedRmsDatas = initSpeedRmsDatas();
        speedRmsAdapter.setItems(speedRmsDatas);
        speedRmsAdapter.notifyDataSetChanged();

        warningMsgAdapter.setItems(new ArrayList<>());
        warningMsgAdapter.notifyDataSetChanged();

        maintenanceRecordAdapter.setItems(new ArrayList<>());
        warningMsgAdapter.notifyDataSetChanged();
    }

    /**
     * 初始化温度压力曲线图基础数据
     *
     * @return
     */
    private List<SensorLineChartData> initTemperaturePressureDatas() {
        List<SensorLineChartData> sensorLineChartDatas = new ArrayList<>();
        for (int i = 0; i < pointCodes.length; i++) {
            SensorLineChartData sensorLineChartData = new SensorLineChartData();
            sensorLineChartData.setCompressorId(currentCompressor.getId());
            sensorLineChartData.setPointCode(pointCodes[i]);
            sensorLineChartDatas.add(sensorLineChartData);
        }
        return sensorLineChartDatas;
    }

    /**
     * 初始化震动曲线图基础数据
     *
     * @return
     */
    private List<SensorLineChartData> initSpeedRmsDatas() {
        List<SensorLineChartData> sensorLineChartDatas = new ArrayList<>();
        for (int i = 0; i < pointCodes2.length; i++) {
            SensorLineChartData sensorLineChartData = new SensorLineChartData();
            sensorLineChartData.setPointCode(pointCodes2[i]);
            sensorLineChartDatas.add(sensorLineChartData);
        }
        return sensorLineChartDatas;
    }

    //切换实时数据和历史数据时 先清空原有数据
    public void initRecycAdapter2() {
        List<SensorLineChartData> sensorLineChartDatas = temperaturePressureAdapter.getItems();
        sensorLineChartDatas.forEach(new Consumer<SensorLineChartData>() {
            @Override
            public void accept(SensorLineChartData sensorLineChartData) {
                List<SensorAgg> sensorAggs = sensorLineChartData.getSensorAggs();
                if (sensorAggs != null) {
                    sensorAggs.forEach(new Consumer<SensorAgg>() {
                        @Override
                        public void accept(SensorAgg sensorAgg) {
                            sensorAgg.setSensorStatisticsData(null);
                        }
                    });
                }
            }
        });
        temperaturePressureAdapter.notifyDataSetChanged();

        sensorLineChartDatas = speedRmsAdapter.getItems();
        sensorLineChartDatas.forEach(new Consumer<SensorLineChartData>() {
            @Override
            public void accept(SensorLineChartData sensorLineChartData) {
                SensorBgg sensorBgg = sensorLineChartData.getSensorBgg();
                if (sensorBgg != null) {
                    sensorBgg.setSensorStatisticsData(null);
                }
            }
        });
        speedRmsAdapter.notifyDataSetChanged();

    }


    /**
     * 根据空压机点位筛选传感器
     *
     * @param pointCode
     * @param sensors
     * @return
     */
    public List<SensorAgg> filterPoints(String pointCode, List<Sensor> sensors) {
        List<Sensor> results = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            results = sensors.stream()
                    .filter(new Predicate<Sensor>() {
                        @Override
                        public boolean test(Sensor sensor) {
                            boolean status;
                            boolean isContains = pointCode.contains(",");
                            if (isContains) {
                                String[] code = pointCode.split(",");
                                status = (TextUtils.equals(sensor.getCompressorPointCode(), code[0]) || TextUtils.equals(sensor.getCompressorPointCode(), code[1]));
                            } else {
                                status = TextUtils.equals(sensor.getCompressorPointCode(), pointCode);
                            }
                            return status;
                        }
                    }).collect(Collectors.toList());
        }
        if (results == null || results.size() == 0) return null;
        List<SensorAgg> sensorAggs = new ArrayList<>();
        for (Sensor sensor : results) {
            SensorAgg sensorAgg = new SensorAgg();
            sensorAgg.setSensor(sensor);
            sensorAggs.add(sensorAgg);
        }
        return sensorAggs;
    }

    /**
     * 根据空压机部位，点位筛选传感器
     *
     * @param partCode
     * @param pointCode
     * @param sensors
     * @return
     */
    public SensorBgg filterParts(String partCode, String pointCode, List<Sensor> sensors) {
        List<Sensor> results = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            results = sensors.stream()
                    .filter(new Predicate<Sensor>() {
                        @Override
                        public boolean test(Sensor sensor) {
                            boolean status = TextUtils.equals(sensor.getCompressorPartCode(), partCode)
                                    && TextUtils.equals(sensor.getCompressorPointCode(), pointCode);
                            return status;
                        }
                    }).collect(Collectors.toList());
        }
        if (results == null || results.size() == 0) return null;
        SensorBgg sensorBgg = new SensorBgg();
        if (results.size() == 1) {
            sensorBgg.setSensor(results.get(0));
        }
        return sensorBgg;

    }

    //筛选当前空压机最新数据
    public SensorLatestData getSensorRealTimeData(Compressor compressor, List<SensorLatestData> data) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            List<SensorLatestData> sensorLatestDataList = data.stream()
                    .filter(new Predicate<SensorLatestData>() {
                        @Override
                        public boolean test(SensorLatestData sensorRealTimeData) {
                            return TextUtils.equals(sensorRealTimeData.getCompressorId(), compressor.getId());
                        }
                    }).collect(Collectors.toList());
            if (sensorLatestDataList != null && sensorLatestDataList.size() > 0) {
                return sensorLatestDataList.get(0);
            }
        }
        return null;
    }

    public boolean checkLoadFinish() {
        readyNo++;
        DLog.e("====数据加载进度=" + readyNo);
        boolean isFinish = false;
        if (readyNo == (currentSensors.size() + 1)) {
            DLog.e("数据加载完成准备刷新...");
            temperaturePressureAdapter.notifyDataSetChanged();
            speedRmsAdapter.notifyDataSetChanged();
            readyNo = 0;
            isFinish = true;
        }
        return isFinish;
    }


    //设置查询开始时间和结束时间
    public void setNewQueryDate(boolean isHistory) {
        if (isHistory) {
            long startDate = 0l;
            if (currentCompressor != null) {
                String installDate = currentCompressor.getInstallDate();
                if (!TextUtils.isEmpty(installDate)) {
                    startDate = TimeUtils.string2Date(installDate, "yyyy-MM-dd").getTime();
                }
            }
            startTime = TimeUtils.date2String(new Date(startDate));
            endTime = TimeUtils.date2String(new Date());
        } else {
            long endLTime = System.currentTimeMillis();
            long starLtTime = endLTime - (15 * 60 * 1000L);
            startTime = TimeUtils.date2String(new Date(starLtTime));
            endTime = TimeUtils.date2String(new Date(endLTime));
        }
    }
}
